package com.zmn.oms.zmn.business.impl.unavailable;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.biz.clue.common.consts.MqConst;
import com.zmn.biz.clue.common.enums.OrderFailReasonEnum;
import com.zmn.biz.clue.common.model.mq.OrderClueMessageDIO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.consts.GlobalConsts;
import com.zmn.gms.common.dio.grid.online.engineer.EngineerBindGridDIO;
import com.zmn.gms.common.dto.online.grid.GridSpDRO;
import com.zmn.gms.dubbo.interfaces.grid.online.engineer.GridEngineerListRemoteService;
import com.zmn.gms.dubbo.interfaces.grid.online.order.GridOrderListRemoteService;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.tag.OrderTagBService;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.model.dio.clue.OrderClueMsgDIO;
import com.zmn.oms.model.dto.order.UnavailableServiceDTO;
import com.zmn.oms.model.dto.tag.OrderTagAddDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceQueryDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceResultDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.order.OrderServiceReason;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.remark.OrderRemark;
import com.zmn.oms.model.entity.remark.OrderRemarkDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.datasync.ElasticSearchDataSyncService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.order.OrderServiceReasonService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkDetailService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import com.zmn.oms.zmn.business.interfaces.unavailable.UnAvailableServiceBService;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class UnAvailableServiceBServiceImpl implements UnAvailableServiceBService {

    @Autowired
    private OrderTagBService orderTagBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private ElasticSearchDataSyncService elasticSearchDataSyncService;
    @Autowired
    private OrderLogBService orderLogBService;
    @Autowired
    private ServItemBService servItemBService;
    @Autowired
    private OrderServiceReasonService orderServiceReasonService;
    @Autowired
    private OrderRemarkService orderRemarkService;
    @Autowired
    private OrderRemarkDetailService orderRemarkDetailService;
    @Autowired
    private BaseCodeService baseCodeService;

    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private ChannelListRemoteService channelListRemoteService;
    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private AreaListRemoteService areaListRemoteService;
    @DubboReference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private CategServProductListRemoteService categServProductListRemoteService;
    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private ProductForeignListRemoteService productForeignListRemoteService;
    @DubboReference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private GridOrderListRemoteService gridOrderListRemoteService;
    @DubboReference(version = com.zmn.gms.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private GridEngineerListRemoteService gridEngineerListRemoteService;

    @Resource
    private DefaultKeyGenerator defaultKeyGenerator;

    @Resource
    private ZmnMQSender zmnMQSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUnAvailableOrder(UnavailableServiceDTO dto) throws OmsBaseException {

        Long orderId = defaultKeyGenerator.generateKey().longValue();
        Date now = DateUtil.getNow();

        // 处理后台产品信息
        this.processProductInfo(dto);

        // 订单信息
        OrderWork orderWork = new OrderWork();
        orderWork.setWorkId(orderId);
        orderWork.setOrderId(orderId);
        orderWork.setType(OrderConsts.ORDER_TYPE_NEW);
        orderWork.setPlat(dto.getPlat());
        orderWork.setPlatWork(dto.getPlat());
        orderWork.setBizType(dto.getBizType());
        orderWork.setChannelId(dto.getChannelId());
        orderWork.setChannelName(dto.getChannelName());
        orderWork.setCityId(dto.getCityId());

        orderWork.setServCategId(dto.getServCategId());
        orderWork.setShowServCategName(dto.getServCategName());
        orderWork.setShowProductId(dto.getShowProductId());
        orderWork.setShowCategOneId(Optional.ofNullable(dto.getShowCategOneId()).orElse(GlobalConsts.NONE));
        orderWork.setShowCategId(Optional.ofNullable(dto.getShowCategId()).orElse(GlobalConsts.NONE));
        orderWork.setProductId(Optional.ofNullable(dto.getProductId()).orElse(GlobalConsts.NONE));
        orderWork.setCategId(Optional.ofNullable(dto.getCategId()).orElse(GlobalConsts.NONE));
        orderWork.setCategOneId(Optional.ofNullable(dto.getCategOneId()).orElse(GlobalConsts.NONE));
        orderWork.setDutyTime(dto.getDutyTime());

        orderWork.setResultStatus(OrderStatusConsts.WORK_RESULT_DISCARD);
        orderWork.setStatus(OrderStatusConsts.WORK_STATUS_INPUT);
        orderWork.setReceiveEntranceId(dto.getReceiveEntranceId());
        orderWork.setReceiveEntranceType(GateTypeConsts.GATE_TYPE_PLAT);
        orderWork.setInputType(OrderConsts.ORDER_INPUT_TYPE_MANUAL);
        orderWork.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
        orderWork.setCompanyName("");
        orderWork.setCreater("系统");
        orderWork.setCreateTime(now);
        orderWork.setUpdater("系统");
        orderWork.setUpdateTime(now);

        // 查询渠道信息
        ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(orderWork.getChannelId());
        ChannelDRO channelDRO = channelResponseDTO.getData();
        if (channelDRO != null) {
            // 合同模式
            orderWork.setBizModeSource(channelDRO.getContractModel());

            orderWork.setChannelName(channelDRO.getName());
            orderWork.setChannelAnotherName(StringUtils.defaultString(channelDRO.getAnotherName()));
            orderWork.setChannelOneId(channelDRO.getPlat());
            orderWork.setChannelTwoId(channelDRO.getParentId());
            orderWork.setSourceChannelId(orderWork.getChannelId());
            orderWork.setSourceChannelOneId(orderWork.getChannelOneId());
            orderWork.setSourceChannelTwoId(orderWork.getChannelTwoId());
        } else {
            log.error("[{}]Remote接口未找到渠道", orderWork.getChannelId());
        }

        // 查询产品组信息
        // 前台产品分组
        CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
        categProductGroupQuery.setBizType(orderWork.getBizType());
        categProductGroupQuery.setServCategId(orderWork.getServCategId());
        categProductGroupQuery.setCategId(orderWork.getShowCategId());
        categProductGroupQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
        ResponseDTO<CategProductGroupDRO> responseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
        CategProductGroupDRO categorySimpleProductGroupDRO = responseDTO.getData();
        if (categorySimpleProductGroupDRO != null) {
            orderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
            orderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
            orderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
        }

        orderWorkService.insertOrderWork(orderWork);

        // 订单详情
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setDetailId(orderId);
        orderDetail.setUserName("未知");
        orderDetail.setContactName("未知");
        orderDetail.setTelephone(dto.getTelephone());
        orderDetail.setProvinceId(dto.getProvinceId());
        orderDetail.setProvinceName(dto.getProvinceName());
        orderDetail.setCityName(dto.getCityName());
        orderDetail.setNaturalCityName(dto.getCityName());
        orderDetail.setCountyId(Optional.ofNullable(dto.getCountyId()).orElse(0));
        // 区县id不为空，查出区县名称
        if (NumberUtil.isNotNullOrZero(orderDetail.getCountyId())) {
            ResponseDTO<AreaDRO> countyAreaResponse = areaListRemoteService.getById(orderDetail.getCountyId());
            if (countyAreaResponse.getData() != null) {
                orderDetail.setCountyName(countyAreaResponse.getData().getName());
            }
        }

        orderDetail.setStreet(dto.getStreet());
        orderDetail.setAddress(dto.getAddress());
        orderDetail.setLongitude(dto.getLongitude());
        orderDetail.setLatitude(dto.getLatitude());
        String remark = "";
        if (StringUtil.isNotBlank(dto.getRemark())) {
            remark = dto.getRemark() + "\n";
        }
        remark += "无法承接原因：" + dto.getReason();
        orderDetail.setRemark(remark);
        // 无法承接线索塞家修匠
        if (Objects.equals(dto.getReason(), "无法承接线索")) {
            List<TagsDRO> list = baseCodeService.listBaseCodeMap(com.zmn.consts.GlobalConsts.PLAT_MARK_ZMN, OrderConsts.BASE_CODE_MAP_ONE_TYPE_JXJ_UN_SERVICE_CITY, dto.getCityId(), null);
            if (CollectionUtil.isNotNullOrEmpty(list)) {
                // 行政子公司和行政服务商都为空，默认塞无法承接线索
                orderDetail.setGridCompanyId(CompanyConsts.ZMN_JXJ_COMPANY_ID);
                orderDetail.setGridCompanyName("家修匠");
                orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_JXJ_MANAGE_COMPANY_ID);
                orderDetail.setGridManageCompanyName("无法承接线索");
            } else {
                // 不属于家修匠，塞无法服务
                orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
                orderDetail.setGridCompanyName("无法服务");
                orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
                orderDetail.setGridManageCompanyName("无法服务线索");
            }
        } else {
            orderDetail.setGridCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_COMPANY_ID);
            orderDetail.setGridCompanyName("无法服务");
            orderDetail.setGridManageCompanyId(CompanyConsts.ZMN_UNABLE_SERVICE_MANAGE_COMPANY_ID);
            orderDetail.setGridManageCompanyName("无法服务线索");
        }

        // 查询网格信息
        log.info("[{}]-查询网格信息入参：[{}]-[{}]-[{}]-[{}]", orderWork.getOrderId(), dto.getLongitude(),
                dto.getLatitude(), dto.getServCategId(), dto.getShowCategId());
        ResponseDTO<GridSpDRO> gridResponseDTO = gridOrderListRemoteService.listGridSpByLatLngAndCategoryId(
                dto.getLongitude(), dto.getLatitude(), String.valueOf(dto.getServCategId()),
                String.valueOf(dto.getShowCategId()));
        log.info("[{}]-查询网格信息出参：[{}]", orderWork.getOrderId(), JSON.toJSONString(gridResponseDTO));
        if (gridResponseDTO.isSuccess() && Objects.nonNull(gridResponseDTO.getData())) {
            orderDetail.setGridId(gridResponseDTO.getData().getGridId());
            orderDetail.setGridName(gridResponseDTO.getData().getGridName());
            EngineerBindGridDIO dio = new EngineerBindGridDIO();
            dio.setGridId(orderDetail.getGridId());
            dio.setTypeId(String.valueOf(orderDetail.getServCategId()));
            ResponseDTO<Boolean> booleanResponseDTO = gridEngineerListRemoteService.gridIsBindEngineerByQuery(dio);
            log.info("[{}]查询网格是否绑定工程师入参：【{}】，出参：【{}】", orderDetail.getDetailId(), JSON.toJSONString(dio), JSON.toJSONString(booleanResponseDTO));
            if (!booleanResponseDTO.isSuccess() || !booleanResponseDTO.getData()) {
                OrderServiceReason reason = new OrderServiceReason();
                reason.setWorkId(orderWork.getWorkId());
                reason.setOrderId(orderWork.getOrderId());
                reason.setSatisfyGrid(GlobalConsts.NO);
                reason.setCreater("系统");
                reason.setUpdater("系统");
                orderServiceReasonService.insert(reason);
            }
        }

        orderDetail.setServCategId(dto.getServCategId());
        orderDetail.setServCategName(dto.getServCategName());
        orderDetail.setCategOneId(Optional.ofNullable(dto.getCategOneId()).orElse(GlobalConsts.NONE));
        orderDetail.setCategId(Optional.ofNullable(dto.getCategId()).orElse(GlobalConsts.NONE));
        orderDetail.setProductId(Optional.ofNullable(dto.getProductId()).orElse(GlobalConsts.NONE));
        orderDetail.setProductInfo(String.format("%s-%s*%s", "", StringUtils.defaultString(dto.getProductName(), dto.getShowProductName()), GlobalConsts.NO));
        orderDetail.setCreater("系统");
        orderDetail.setCreateTime(now);
        orderDetail.setUpdater("系统");
        orderDetail.setUpdateTime(now);
        orderDetailService.insertOrderDetail(orderDetail);

        // 订单产品
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOrderId(orderId);
        orderProduct.setBrandId(GlobalConsts.NONE);
        orderProduct.setCategOneId(Optional.ofNullable(dto.getCategOneId()).orElse(GlobalConsts.NONE));
        orderProduct.setCategOneName(StringUtils.defaultString(dto.getCategOneName(), ""));
        orderProduct.setShowCategOneId(Optional.ofNullable(dto.getShowCategOneId()).orElse(GlobalConsts.NONE));
        orderProduct.setShowCategOneName(StringUtils.defaultString(dto.getShowCategOneName(), ""));
        orderProduct.setCategId(Optional.ofNullable(dto.getCategId()).orElse(GlobalConsts.NONE));
        orderProduct.setCategName(StringUtils.defaultString(dto.getCategName(), ""));
        orderProduct.setShowCategId(Optional.ofNullable(dto.getShowCategId()).orElse(GlobalConsts.NONE));
        orderProduct.setShowCategName(StringUtils.defaultString(dto.getShowCategName(), ""));
        orderProduct.setProductId(Optional.ofNullable(dto.getProductId()).orElse(GlobalConsts.NONE));
        orderProduct.setProductName(StringUtils.defaultString(dto.getProductName(), ""));
        orderProduct.setShowProductId(Optional.ofNullable(dto.getShowProductId()).orElse(GlobalConsts.NONE));
        orderProduct.setShowProductName(StringUtils.defaultString(dto.getShowProductName(), ""));
        orderProduct.setShowProductUnit("");
        orderProduct.setNumber(GlobalConsts.NO);
        orderProduct.setCreater("系统");
        orderProduct.setCreateTime(now);
        orderProduct.setUpdateTime(now);
        List<OrderProduct> orderProductList = Lists.newArrayList(orderProduct);
        orderProductService.insertOrderProductList(orderProductList);

        // 保存工单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderWork.getOrderId());
        orderLog.setWorkId(orderWork.getWorkId());

        StringBuilder sb = new StringBuilder();
        sb.append("地址信息：");
        sb.append(orderDetail.getProvinceName()).append(orderDetail.getCityName()).append(orderDetail.getCountyName())
                .append(StringUtils.defaultString(orderDetail.getStreet())).append(StringUtils.defaultString(orderDetail.getAddress()))
                .append("经纬度：").append(orderDetail.getLongitude()).append(",").append(orderDetail.getLatitude());
        sb.append("\n");
        sb.append("产品信息：");
        sb.append(String.format("前台产品[%s]-后台产品[%s],数量:%s,品牌:%s", StringUtils.defaultIfBlank(orderProduct.getShowProductName(), "-"), StringUtils.defaultIfBlank(orderProduct.getProductName(), "-"),orderProduct.getNumber(), StringUtils.defaultIfBlank(orderProduct.getBrandName(), "-")));

        orderLog.setContent(sb.toString());
        orderLog.setType(OrderLogConsts.ORDER_LOG_TYPE_WAIT_DISTRIBUTE);
        orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(OrderLogConsts.ORDER_LOG_TYPE_INPUT));
        orderLog.setBeforeStatus(orderWork.getStatus());
        orderLog.setBeforeStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setBeforeResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
        orderLog.setBeforeResultStatusName(OrderStatusConsts.getWorkResultStatusName(OrderStatusConsts.WORK_RESULT_DOING));
        orderLog.setAfterStatus(orderWork.getStatus());
        orderLog.setAfterStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setAfterResultStatus(orderWork.getResultStatus());
        orderLog.setAfterResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        OrderWorkLogUtils.processOrderLogOperater(orderLog, null);
        orderLogBService.save(orderLog);

        // 添加未成单标签
        OrderTagAddDTO orderTagAddDTO = new OrderTagAddDTO();
        orderTagAddDTO.setOrderId(orderId);
        orderTagAddDTO.setWorkId(orderId);
        orderTagAddDTO.setTagIdList(Lists.newArrayList(OrderTagConsts.TAG_ID_UN_AVAILABLE_SERVICE));
        orderTagBService.addOrderTag(orderTagAddDTO);

        // 保存备注
        OrderRemark orderRemark = new OrderRemark();
        orderRemark.setOrderId(orderId);
        orderRemark.setWorkId(orderId);
        orderRemark.setType(OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        orderRemark.setOperateUserId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        orderRemark.setOperateUserType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        orderRemarkService.insertOrderRemark(orderRemark);

        // 保存备注详情
        Long remarkId = orderRemark.getRemarkId();
        List<OrderRemarkDetail> detailList = Lists.newArrayList();
        OrderRemarkDetail detail = new OrderRemarkDetail();
        detail.setRemarkId(remarkId);
        detail.setOrderId(orderId);
        detail.setWorkId(orderId);
        detail.setType(OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        switch (dto.getReason()) {
            case "无法承接线索":
                detail.setMapId(117);
                break;
            case "暂无网格覆盖":
                detail.setMapId(118);
                break;
            case "暂无服务商可服务":
                detail.setMapId(119);
                break;
            default:
                detail.setMapId(GlobalConsts.NONE);
                break;
        }
        detail.setMapName(dto.getReason());
        detail.setCategory(GlobalConsts.NONE);
        detail.setCreater("系统");
        detailList.add(detail);
        orderRemarkDetailService.insertOrderRemarkList(detailList);

        // 同步es
        elasticSearchDataSyncService.syncWorkIndex(orderId);
    }

    @Override
    public void pushOrderWorkToClue(OrderClueMsgDIO clueMsgDIO, String failReason) {
        OrderClueMessageDIO dio = new OrderClueMessageDIO();
        dio.setSourceId(clueMsgDIO.getSourceId());
        dio.setSourceType(clueMsgDIO.getSourceType());
        dio.setLowerId(clueMsgDIO.getLowerId());
        dio.setLowerStatus(clueMsgDIO.getLowerStatus());
        dio.setPlat(clueMsgDIO.getPlat());
        dio.setPhone(clueMsgDIO.getPhone());
        dio.setPhone2(clueMsgDIO.getPhone2());
        dio.setPhone3(clueMsgDIO.getPhone3());
        dio.setUserName(clueMsgDIO.getUserName());
        dio.setGender(clueMsgDIO.getGender());
        dio.setProvinceId(clueMsgDIO.getProvinceId());
        dio.setProvinceName(clueMsgDIO.getProvinceName());
        dio.setCityId(clueMsgDIO.getCityId());
        dio.setCityName(clueMsgDIO.getCityName());
        dio.setCountyId(clueMsgDIO.getCountyId());
        dio.setCountyName(clueMsgDIO.getCountyName());
        dio.setStreetSource(clueMsgDIO.getStreetSource());
        dio.setStreetId(clueMsgDIO.getStreetId());
        dio.setStreetName(clueMsgDIO.getStreetName());
        dio.setCommunityId(clueMsgDIO.getCommunityId());
        dio.setCommunityName(clueMsgDIO.getCommunityName());
        dio.setAddress(clueMsgDIO.getAddress());
        dio.setCooperateId(clueMsgDIO.getCooperateId());
        dio.setCooperateName(clueMsgDIO.getCooperateName());
        switch (failReason) {
            case "无法承接线索":
                dio.setFailReason(OrderFailReasonEnum.NO_RECEIVE.getCode());
                break;
            case "暂无服务商可服务":
                dio.setFailReason(OrderFailReasonEnum.NO_PROVIDER.getCode());
                break;
            case "暂无网格覆盖":
                dio.setFailReason(OrderFailReasonEnum.NO_GRID.getCode());
                break;
            default:
                dio.setFailReason(OrderFailReasonEnum.OTHER.getCode());
                break;
        }
        String message = JSON.toJSONString(dio);
        String key = "biz_clue_source_type_" + DateUtil.getNowTimestampMillis();
        log.debug("线索数据同步给线索系统key:[{}]，message:[{}] 数据源类型:[{}]", key, message, clueMsgDIO.getSourceType());
        zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_BIZ_CLUE, MqConst.ORDER_CLUE_TAG, key, message);
    }

    /**
     * 如果只有前端产品查找后台产品信息
     * @param dto
     */
    private void processProductInfo(UnavailableServiceDTO dto) {
        if (NumberUtil.isNotNullOrZero(dto.getProductId())) {
            return;
        }
        // 查询前台产品对应后台产品
        BackProductPriceQueryDTO backProductPriceQueryDTO = BackProductPriceQueryDTO
                .builder()
                .showProductId(dto.getShowProductId())
                .bizType(dto.getBizType())
                .brandId(GlobalConsts.NONE)
                .channelId(dto.getChannelId())
                .cityId(dto.getCityId())
                .platWork(dto.getPlat())
                .build();
        BackProductPriceResultDTO backProductPriceResultDTO = servItemBService.queryBackProductPrice(backProductPriceQueryDTO);
        if (Objects.isNull(backProductPriceResultDTO)) {
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(dto.getProductId()));
            defaultEcProductQuery.setChannelId(dto.getChannelId());
            defaultEcProductQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            ResponseDTO<List<ProductBaseDRO>> listResponseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            List<ProductBaseDRO> list = listResponseDTO.getData();
            if (!listResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(list)) {
                log.info("产品数据配置有误，[{}]没有映射后端产品或已禁用", dto.getShowProductId());
                return;
            }
            ProductBaseDRO product = list.get(0);
            dto.setCategId(product.getCategId());
            dto.setCategName(product.getCategName());
            dto.setCategOneId(product.getCategOneId());
            dto.setCategOneName(product.getCategOneName());
            return;
        }

        ProductBaseQuery productDIO = new ProductBaseQuery();
        productDIO.setStatus(GlobalConsts.YES);
        productDIO.setProductId(backProductPriceResultDTO.getProductId());
        ResponseDTO<List<ProductBaseDRO>> productDROResp = productForeignListRemoteService.listBaseDROByQuery(productDIO);
        if (CollectionUtil.isNullOrEmpty(productDROResp.getData())) {
            return;
        }
        ProductBaseDRO backProductBase = productDROResp.getData().get(0);
        dto.setProductId(backProductBase.getProductId());
        dto.setProductName(backProductBase.getProductName());
        dto.setCategOneId(backProductBase.getCategOneId());
        dto.setCategOneName(backProductBase.getCategOneName());
        dto.setCategId(backProductBase.getCategId());
        dto.setCategName(backProductBase.getCategName());
    }
}
